package com.daisuxia.risk.service;

import java.net.URLDecoder;

import java.net.URLEncoder;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.back.utils.WebClient;
import com.daisuxia.mg.model.UserGridResponse;
import com.daisuxia.mg.service.UserGridApi;
import com.daisuxia.risk.pojo.RiskOrders;
import com.daisuxia.risk.utils.ConstantRisk;
import com.daisuxia.risk.utils.PropertiesUtils;
import com.daisuxia.risk.utils.yx.OuterEcFormat;
import com.daisuxia.risk.utils.yx.RC4_128_V2;
import com.daisuxia.risk.utils.yx.RSA_1024_V2;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.util.JSONUtil;
import com.daisuxia.web.util.OrderNoUtil;
/**
 * 宜信 
 * @author zhangsh Tel:13817876783
 * @date 2017年10月18日 上午9:20:56
 * @Title: YxService
 * @ClassName: YxService
 * @Description:
 */
@Service
public class YxService implements IYxService {
	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private IRiskOrdersService riskOrdersService;

	@Override
	public void findForYx() {

	}

	@Override
	public ServiceResult sendYx(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			Object userName = params.get("userName");
			Object cardNum = params.get("cardNum");
			Object userId = params.get("userId");
			if (userName != null && cardNum != null && userId != null) {
				RiskOrders orders = new RiskOrders();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.YX);
				orders.setAct(ConstantRisk.YX_BORROW);
				orders.setOrderNo(OrderNoUtil.getInstance().getUUID());
				orders.setReqParams("userId=" + userId + ";userName=" + userName + ";cardNum=" + cardNum);
				logger.info("yx card "+cardNum);
//				logger.info("sendYx send  " + orders.toString());
				riskOrdersService.insert(orders);
				LinkedHashMap<String, String> map2 = SysCacheUtils.getConfigParams(BackConfigParams.YX);

				String url = map2.get("YX_URL");
				String name = map2.get("YX_NAME");
				String pwd = map2.get("YX_KEY");
				RSAPublicKey rsaKey = RSA_1024_V2.gainRSAPublicKeyFromCrtFile(PropertiesUtils.getProperty(ConstantRisk.FILE_CRT_YX));
				String encUserid = RSA_1024_V2.encodeByPublicKey(rsaKey, name);
				JSONObject data = new JSONObject();
				data.put("name", userName);
				data.put("idNo", cardNum);
				data.put("queryReason", "10");
				JSONObject innerJson = new JSONObject();
				innerJson.put("tx", "101");
				innerJson.put("data", data);
				String encParams = URLEncoder.encode(RC4_128_V2.encode(innerJson.toJSONString(), pwd), "UTF-8");
				Map<String, String> paraMap = new HashMap<String, String>();
				paraMap.put("userid", encUserid);
				paraMap.put("params", encParams);
				String result = WebClient.getInstance().doPost(url, paraMap);
//				logger.info("sendYx return " + result);
				if (StringUtils.isNotBlank(result)) {
					OuterEcFormat rec = (OuterEcFormat) JSONUtil.jsonToBean(result, OuterEcFormat.class);
					int code = rec.getErrorCode();
					String msg = rec.getMessage();
					String decodeRes = null;
					if (code == 1) {
						decodeRes = RC4_128_V2.decode(URLDecoder.decode(rec.getParams(), "UTF-8"), pwd);
						logger.info("解密响应：" + decodeRes);
						//查询成功但是无相应的数据
						serviceResult = new ServiceResult(ServiceResult.SUCCESS, decodeRes);
					} else if (code == 0) {
						decodeRes = RC4_128_V2.decode(URLDecoder.decode(rec.getParams(), "UTF-8"), pwd);
						logger.info("解密响应：" + decodeRes);
						orders.setStatus(RiskOrders.STATUS_SUC);
						serviceResult = new ServiceResult(ServiceResult.SUCCESS, decodeRes);
					} else {
						decodeRes = result;
						serviceResult = new ServiceResult("300", msg);
					}
					orders.setReturnParams(decodeRes);
					riskOrdersService.update(orders);
				} else {
					orders.setReturnParams("return null");
					serviceResult = new ServiceResult("100", "返回空或请求报错");
				}
				riskOrdersService.update(orders);

			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("sendYx error ,params=" + params, e);
		}
		return serviceResult;
	}

}
